package worker

import (
	"GoCrontab/crontab/common"
	"fmt"
	"math/rand"
	"os/exec"
	"time"
)

//任务执行器
type Executor struct {
}

var (
	GlobalExecutor *Executor
)

func (e *Executor) ExecuteJob(jobInfo *common.JobExecuteInfo) {
	go func() {
		var (
			cmd     *exec.Cmd
			err     error
			output  []byte
			result  *common.JobExecuteResult
			jobLock *JobLock
		)
		result = &common.JobExecuteResult{
			ExecuteInfo: jobInfo,
			Output:      make([]byte, 0),
		}
		//初始化分布式锁
		jobLock = GlobalJobManager.CreateJobLock(jobInfo.Job.Name)
		//记录任务开始时间
		result.StartTime = time.Now()
		//随机睡眠0-1s
		time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
		err = jobLock.TryLock()
		defer jobLock.Unlock()

		if err != nil {
			result.Err = err
			result.EndTime = time.Now()
		} else {
			result.StartTime = time.Now()
			//cmd = exec.CommandContext(jobInfo.CancelCtx, "/bin/bash", "-c", jobInfo.Job.Command)
			// 利星行台式机上
			cmd = exec.CommandContext(jobInfo.CancelCtx, "C:\\Program Files\\Git\\bin\\bash.exe", "-c", jobInfo.Job.Command)

			output, err = cmd.CombinedOutput()
			if err != nil {
				fmt.Println("cmd error is", err)
			}
			result.EndTime = time.Now()
			result.Output = output
			result.Err = err
		}
		//任务执行完成后，把执行的结果返回给Scheduler，后者会从map table中删除掉执行记录
		GlobalScheduler.PushJobResult(result)

	}()
}

// 初始化执行器
//目前为空
func InitExecutor() (err error) {
	GlobalExecutor = &Executor{}
	return
}
